package com.aiden.app.common;

import java.util.ArrayList;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;

/**
 * Descriptions：
 * <p>
 * Author：ChenME
 * Date：2019/4/24
 * Email：ibelieve1210@163.com
 */
public class SignatureUtil {

//    private static final Logger logger = LoggerFactory.getLogger(SignatureUtil.class);
public final static String SIGN_KEY = "202006250b4c43127ec02edce69f6a5d";
    /**
     * 签名算法
     *
     * @param o
     *            要参与签名的数据对象
     * @return 签名
     * @throws IllegalAccessException
     */
    public static String getObjSign(Object o) throws IllegalAccessException {
        ArrayList<String> list = new ArrayList<>();
        Class<?> cls = o.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            if (f.get(o) != null && f.get(o) != "") {
                list.add(f.getName() + "=" + f.get(o) + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + SIGN_KEY;
        System.out.println("Object签名参数：" + result);
        result = MD5Util.encrypt(result).toUpperCase();
        System.out.println("Object签名：" + result);
        return result;
    }

    /**
     * 签名算法
     *
     * @param map
     *            要参与签名的数据对象
     * @return 签名
     * @throws Exception
     */
    public static String getMapSign(Map<String, Object> map) {
        ArrayList<String> list = new ArrayList<>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + SIGN_KEY;
        System.out.println("Map签名参数：" + result);
        result = MD5Util.encrypt(result).toUpperCase();
        System.out.println("Map签名：" + result);
        return result;
    }
}
